// 主界面
;
define(function(require, exports, module) {
	'use strict';
	var util = require("util");
	var base = require("base");
	var router = require("../hash/pageRouter");
	var css_this = require("./tallyListGenerate.css");
	var newTaskDetail = require("./newTaskDetail.js");
	var dialog = require("dialog");
	var validate = require("validate");
	var databind = require("databind");
	var clerkName;
	var pageIndex = 1,
		pageSize = 10,
		totalPageCount = 1,
		totalRecordCount = 0; //分页初始化
	var imgSrc;
	var recieveNoticeId;
	var taskDetail;
	var tallyingDetail;
	var caseQueue = 0;
	var left;
	var noticeState;
	var type;
	var init = function(page) {
		newTaskDetail.init(page);
		recieveNoticeId = page.params.recieveNoticeId || base.getUrlParam("recieveNoticeId");
		var tallyingId = page.params.tallyingId || base.getUrlParam("tallyingId"); //理货单Id
		type = page.params.type || base.getUrlParam("type");
		left = page.params.left || base.getUrlParam("left");
		noticeState = page.params.noticeState || base.getUrlParam("noticeState");
		loadTaskDetail(recieveNoticeId);
		if (tallyingId != null && tallyingId.length > 0) {
			updateTallying(tallyingId);
		}

		initEvent();
		router.init();

		$("#leftMenu1").find(".leftMenu-item").removeClass("leftMenu-active");
		$("#leftMenu1 #undoneTaskList").parent(".leftMenu-item").addClass("leftMenu-active");
	};
	var initEvent = function() {
		//若未登录，则返回登陆页面
		if (base.getData("sid") == null || base.getData("sid") == "" || base.getData("sid") == undefined) {
			top.location.href = "../login/login.html";
		}
		$(".page-header").on("click", ".taskDetail", function() {
			router.route("newTaskList/newTaskDetail.html?recieveNoticeId=" + recieveNoticeId + "&noticeState=" + noticeState + "&left=" + left, true);
		});

		//点击
		$(".newTaskList").unbind("click").click(function() {
			top.location.href = "../newTaskList/newTaskList.html?noticeState=" + noticeState + "&left=" + left;
		});
		//快速创建箱量
		//		$(".page-content").on("click", ".fastAdd", function() {
		//			var number =$(".containerQuantity").val();
		//			if(number.length==0){
		//				base.alert(2, "集装箱数量不能为空！");
		//				return ;
		//			}
		//			for(var i=0;i<number;i++){
		//				addContainer($(".addMoreBtn"));
		//				addCommodityEvent();
		//			}
		//		});
		//		
		//删除集装箱
		$(".page-content-main-content").on("click", ".delete", function() {
			$(this).parent(".page-content-main-content-item").remove();
		});

		//添加集装箱
		$(".page-content").on("click", ".addMoreBtn", function() {
			caseQueue += 1;
			addContainer($(this), caseQueue);
			addCommodityEvent();
			$(".caseQuantity").unbind("change").change(function() {
				caseQueue += parseInt($(this).val());
			});
		});

		$(".page-content").on("click", ".handle-designate", function() {
			dialog.showDialog($("#designateStaffList"), function() {
				arrangeStaff();
			});
		});

		$(".page-content").on("click", ".handle-submit", function() {
			createTallyRecord();
		});



		//上传附件
		$("#uploadFile").on('change', function() {
			uploadFile();
		});

		//

		//只支持IE输入框变化
		$('#clerkPerson').bind('input propertychange', function() {
			clerkPersonAutocomplete();
		});
		//只支持输入框变化
		$('#clerkPerson').bind('input oninput', function() {
			clerkPersonAutocomplete();
		});

	};
	//绑定货物相关事件
	var commodityBulkstockEvent = function() {
			//删除所在行
			$(".deleteCommodity").unbind("click").click(function() {
				$(this).parent().parent().remove();
			});

			//绑定点击货物事件
			$(".tallyBulkstockId").unbind("change").change(function() {
				var bulkstock;
				var bulkstockId = $(this).val();
				$.each(taskDetail.datas[0].bulkstocks, function(i, val) {
					if (bulkstockId == val.bulkstockId) {
						bulkstock = val;
					}
				});
				$(this).attr("id", bulkstockId);
				databind.fillForm($(this).parent().parent(), bulkstock);
				$(this).parent().parent().find(".plannedQuantity").attr("max", bulkstock.quantity);
				$(this).parent().parent().find(".plannedQuantity").attr("weightScale", bulkstock.weight / bulkstock.quantity); //重量比例
				$(this).parent().parent().find(".plannedQuantity").attr("volumeScale", bulkstock.volume / bulkstock.quantity); //体积比例
				$(this).parent().parent().find(".plannedQuantity").val(bulkstock.quantity);
				$(this).parent().parent().find(".plannedWeight").val(bulkstock.weight);
				$(this).parent().parent().find(".plannedVolume").val(bulkstock.volume);
				$(this).parent().parent().find(".quantityMax").html(bulkstock.quantity);
				$(this).parent().parent().find(".weightMax").html(bulkstock.weight);
				$(this).parent().parent().find(".volumeMax").html(bulkstock.volume);
			});

			//plannedQuantity输入框焦点离开事件
			$(".plannedQuantity").on("blur", function() {
				var max = $(this).attr("max");
				var weightScale = $(this).attr("weightScale");
				var volumeScale = $(this).attr("volumeScale");
				if ($(this).val().search("^-?\\d+$") != 0) {
					base.alert(2, "请输入一个整数");
					return false;
				}
				var plannedQuantity = $(this).val();
				if (parseFloat(plannedQuantity) > parseFloat(max)) {
					base.alert(2, "计划理货不能大于实际收货数量" + max);
				}

				//数量和重量和体积要联动
				$(this).parent().parent().find(".plannedWeight").val((plannedQuantity * weightScale).toFixed(0));
				$(this).parent().parent().find(".plannedVolume").val((plannedQuantity * volumeScale).toFixed(0));
			});
		}
		//绑定增加货箱相关事件
	var addCommodityEvent = function() {

		$(".addCommodity").unbind("click").click(function() {

			addCommodityTr($(this));
			var caseNumber = $(this).parent().parent(".page-content-main-content-item").find(".caseQueue").val();
			$(this).parent().parent(".page-content-main-content-item").find(".bulkstockCaseQueue").val(caseNumber); //每个货物带集装箱号

			loadTallyBulkstock();
			commodityBulkstockEvent();
		});
	}

	//修改理货任务
	var updateTallying = function(tallyingId) {
		inquireTallyingDetail(tallyingId);
		$(".tallying").attr("action", "updateTallying");


	}

	//获取理货任务
	var inquireTallyingDetail = function(tallyingId) {
			base.fnAjax({
				action: "inquireTallyingDetail.json",
				async: false,
				oData: {
					tallyingId: tallyingId
				}, //传递参数
				fnSuccess: function(data) {
					if (data.status == 200) {
						tallyingDetail = data;
						loadTaskDetail(data.datas[0].recieveNoticeId);
						databind.fillForm($(".tallying"), data.datas[0]);
						containerCommodityTpl($(".addMoreBtn")); //生成HTML
						var tpl = $(".containerCommodityTpl").html();
						var html = juicer(tpl, data.datas[0]); //给集装箱赋值
						$(".containerCommodity").html(html);
						addCommodityEvent();
						commodityBulkstockEvent();
						loadTallyBulkstock();
						fillFormQuantityMax();
						caseQueue = data.datas[0].containerInventorys.length;
						
						if(type=="readOnly"){
							databind.disableInput($("#tallyListGenerate"));
						}
					} else {
						base.alert(2, "信息获取失败");
					}
				}
			});
		}
		//理货数量，重量和体积
	var fillFormQuantityMax = function() {
		$.each($(".tallyBulkstockId"), function(i, val) {
			var bulkstock;
			var bulkstockId = $(this).attr("id");
			$.each(taskDetail.datas[0].bulkstocks, function(i, val) {
				if (bulkstockId == val.bulkstockId) {
					bulkstock = val;
				}
			});
			$(this).parent().parent().find(".plannedQuantity").attr("max", bulkstock.quantity);
			$(this).parent().parent().find(".plannedQuantity").attr("weightScale", bulkstock.weight / bulkstock.quantity); //重量比例
			$(this).parent().parent().find(".plannedQuantity").attr("volumeScale", bulkstock.volume / bulkstock.quantity); //体积比例
			$(this).parent().parent().find(".plannedQuantity").val(bulkstock.quantity);
			$(this).parent().parent().find(".quantityMax").html(bulkstock.quantity);
			$(this).parent().parent().find(".weightMax").html(bulkstock.weight);
			$(this).parent().parent().find(".volumeMax").html(bulkstock.volume);
		});

	}

	//修改的默认集装箱和货物模板
	var containerCommodityTpl = function(dom) {

		var text = '<script type="text/template" class="containerCommodityTpl">';
		text += '		{@each containerInventorys as it,index}';
		text += '		<div class="page-content-main-content-item">';
		text += '		<img src="../../../res/images/icon/delete.png" class="delete"/>';
		text += '		<p>';
		text += '<input type="hidden" name="caseQueue" value="${index}" class="caseQueue" />';
		text += '			<span class="subitem">箱号：<input type="text" value="${it.caseNumber}" placeholder="箱号" class="caseNumber" name="caseNumber" minLength="1" maxLength="255" />';
		text += '			</span>';
		text += '			<span class="subitem none">同款箱量：<input type="hidden" value="1"  name="caseQuantity" class="caseQuantity"  />';
		text += '			</span>';
		text += '			<span class="subitem">箱型尺寸：';
		text += '<select name="caseSize" value="${it.caseSize}">';
		text += '					<option value="20GP">20GP</option>';
		text += '					<option value="20HQ">20HQ</option>';
		text += '					<option value="40GP">40GP</option>';
		text += '					<option value="40HQ">40HQ</option>';
		text += '					<option value="40RH">40RH</option>';
		text += '				</select>';
		text += '			</span><input type="hidden" name="inventoryId" value="${it.inventoryId}" />';
		text += '			<label class="addCommodity"></label>';
		text += '		</p>';
		text += '		<div class="content">';
		text += '		<div class="clear"></div>';
		text += '			<table class="table">';
		text += '				<thead>';
		text += '					<tr>';
		text += '						<th>货物名称</th>';
		text += '						<th>规格型号</th>';
		text += '						<th>计划﻿理货数量</th>';
		text += '						<th>重量(吨)</th>';
		text += '						<th>体积(m<sup>3</sup>)</th>';
		text += '						<th>托盘号</th>';
		text += '						<th>操作</th>';
		text += '					</tr>';
		text += '				</thead>';
		text += '				<tbody class="commodityTable">';
		text += '			{@each it.containerBulkstocks as that}';
		text += '<tr><td>';
		text += '<input type="hidden"  name="bulkstockCaseNumber" value="${it.caseNumber}" class="bulkstockCaseNumber arrayTally" />';
		text += '<input type="hidden" class="arrayTally" name="containerBulkstockId" value="${that.containerBulkstockId}" />';
		text += '<input type="hidden" name="bulkstockCaseQueue" value="${index}"  class="bulkstockCaseQueue bulkstockCaseNumber arrayTally" />';
		text += '<select class="tallyBulkstockId field-input weights"  name="bulkstockId" id="${that.bulkstockId}">';

		text += '</select></td>';
		text += '<td><input type="text" value="${that.specification}" class="arrayTally" name="specification" placeholder="规格型号" readonly="readonly" class="noInput"/></td>';
		text += '<td>';
		text += '<input type="text" value="${that.plannedQuantity}" placeholder="计划﻿理货数量" isNULL="1" codeName="计划﻿理货数量" class="arrayTally plannedQuantity" name="plannedQuantity" minLength="1" maxLength="255" />';
		text += '<br/>理货总数量：<span class="quantityMax"></span>		';
		text += '</td>';
		text += '<td><input type="text" value="${that.weight}"  placeholder="计划理货重量" isNULL="1" codeName="计划理货重量" class="arrayTally plannedWeight" name="plannedWeight" minLength="1" maxLength="255" />';
		text += '<br/>理货总重量：<span class="weightMax"></span>		';
		text += '</td>';
		text += '<td><input type="text" value="${that.volume}" placeholder="计划理货体积" isNULL="1" codeName="计划理货体积" class="arrayTally plannedVolume" name="plannedVolume" minLength="1" maxLength="255" />';
		text += '<br/>理货总体积：<span class="volumeMax"></span>		';
		text += '</td>';
		//		text += '<td><input type="text" value="${that.plannedQuantity}" class="arrayTally plannedQuantity" placeholder="计划﻿理货数量" name="plannedQuantity"  /></td>';
		//		text += '<td><input type="text" value="${that.weight}" class="arrayTally plannedWeight" placeholder="重量" name="weight" minLength="1" maxLength="255" /></td>';
		//		text += '<td><input type="text" value="${that.volume}" class="arrayTally plannedVolume" placeholder="体积" name="volume" minLength="1" maxLength="255" /></td>';
		text += '<td><input type="text" value="${that.trayNumber}" class="arrayTally" placeholder="托盘号" name="trayNumber" minLength="1" maxLength="255" /></td>';
		text += '<td><a class="deleteCommodity" href="javascript:void(0)">删除</a></td></tr>';
		text += '{@/each}';
		text += '				</tbody>';
		text += '			</table>';
		text += '		</div>';
		text += '		<div class="clear"></div>';
		text += '	</div>';
		text += '	{@/each}';
		text += '	</script>';

		text += '<script type="text/template" class="tallyBulkstockTpl">';
		text += '<option value="">未选</option>';
		text += '{@each bulkstocks as them}';

		text += '<option value="${them.bulkstockId}">${them.bulkstockName}</option>';
		text += '{@/each}';
		text += '</script>';
		dom.before(text);
	}

	//添加一个集装箱
	var addContainer = function(dom, i) { //i代表集装箱数量
		var text = '<div class="page-content-main-content-item">';
		text += '		<img src="../../../res/images/icon/delete.png" class="delete"/>';
		text += '		<p>';
		text += '<input type="hidden" name="caseQueue" value="' + i + '" class="caseQueue" />';
		text += '			<span class="subitem">箱号：<input type="text" placeholder="箱号" class="caseNumber arrayTally" name="caseNumber" minLength="1" maxLength="255" />';
		text += '			</span>';
		text += '			<span class="subitem">同款箱量：<input type="text" value="1" name="caseQuantity" class="caseQuantity"  />';
		text += '			</span>';
		text += '			<span class="subitem">箱型尺寸：';
		text += '<select name="caseSize" value="${it.caseSize}">';
		text += '					<option value="20GP">20GP</option>';
		text += '					<option value="20HQ">20HQ</option>';
		text += '					<option value="40GP">40GP</option>';
		text += '					<option value="40HQ">40HQ</option>';
		text += '					<option value="40RH">40RH</option>';
		text += '				</select>';
		text += '			</span>';
		text += '			<label class="addCommodity"></label>';
		text += '		</p>';
		text += '		<div class="content">';
		text += '		<div class="clear"></div>';
		text += '			<table class="table">';
		text += '				<thead>';
		text += '					<tr>';
		text += '						<th>货物名称</th>';
		text += '						<th>规格型号</th>';
		text += '						<th>计划﻿理货数量</th>';
		text += '						<th>重量(吨)</th>';
		text += '						<th>体积(m<sup>3</sup>)</th>';
		text += '						<th>托盘号</th>';
		text += '						<th>操作</th>';
		text += '					</tr>';
		text += '				</thead>';
		text += '				<tbody class="commodityTable">';
		text += '				</tbody>';
		text += '			</table>';
		text += '		</div>';
		text += '		<div class="clear"></div>';
		text += '	</div>';
		dom.before(text);

	}

	//添加货物一行
	var addCommodityTr = function(dom) { //i代表集装箱数量
			var text = '<tr><td>';
			text += '<input type="hidden" name="bulkstockCaseQueue"  class="bulkstockCaseQueue bulkstockCaseNumber arrayTally" />';
			text += '<select class="tallyBulkstockId field-input weights"  name="bulkstockId">';
			text += '<script type="text/template" class="tallyBulkstockTpl">';
			text += '<option value="">未选</option>';
			text += '{@each bulkstocks as it}';
			text += '<option value="${it.bulkstockId}">${it.bulkstockName}</option>';
			text += '{@/each}';
			text += '</script>';
			text += '</select></td>';
			text += '<td><input type="text" name="specification" class="arrayTally" placeholder="规格型号" readonly="readonly" class="noInput"/></td>';
			text += '<td>';
			text += '<input type="text" placeholder="计划﻿理货数量" isNULL="1" codeName="计划﻿理货数量"  class="arrayTally plannedQuantity" name="plannedQuantity" minLength="1" maxLength="255" />';
			text += '<br/>理货总数量：<span class="quantityMax"></span>		';
			text += '</td>';
			text += '<td><input type="text" placeholder="计划﻿理货重量" isNULL="1" codeName="计划﻿理货重量"  class="arrayTally plannedWeight" name="plannedWeight" minLength="1" maxLength="255" />';
			text += '<br/>理货总重量：<span class="weightMax"></span>		';
			text += '</td>';
			text += '<td><input type="text" placeholder="计划﻿理货体积" isNULL="1" codeName="计划﻿理货体积"  class="arrayTally plannedVolume" name="plannedVolume" minLength="1" maxLength="255" />';
			text += '<br/>理货总体积：<span class="volumeMax"></span>		';
			text += '</td>';
			text += '<td><input type="text"  class="arrayTally" placeholder="托盘号" name="trayNumber" minLength="1" maxLength="255" /></td>';
			text += '<td><a class="deleteCommodity" href="javascript:void(0)">删除</a></td></tr>';
			dom.parent().parent().children(".content").children(".table").children(".commodityTable").before(text);

		}
		//动态加载货物列表数据
	var loadTallyBulkstock = function() {
		var tpl = $(".tallyBulkstockTpl").html();
		var html = juicer(tpl, taskDetail.datas[0]);
		$(".tallyBulkstockId").html(html);
		$.each($(".tallyBulkstockId"), function(i, val) {
			$(this).val(val.id);
		});

	}

	//生成理货任务
	var createTallyRecord = function() {
		$.each($(".arrayTally"), function(i, val) {
			if (val.value == undefined || val.value.length == 0) {
				if (val.name == "plannedQuantity" || val.name == "bulkstockId") {
					$(this).val(0);
				} else {
					$(this).val(" ");
				}

			}
		});
		databind.submitDom($(".tallying"), function() {
			var isTrue = true;
			$.each($(".plannedQuantity"), function(i, val) {
				var max = $(this).attr("max");
				if ($(this).val().search("^-?\\d+$") != 0) {
					base.alert(2, "请输入一个整数");
					return false;
				}
				var plannedQuantity = $(this).val();
				if (parseFloat(plannedQuantity) > parseFloat(max)) {
					base.alert(2, "计划理货" + plannedQuantity + "不能大于实际收货数量" + max);
					isTrue = false;
				}
			});

			if (isTrue) {
				base.alert(1, "创建理货任务成功");
				router.route("newTaskList/undoneCargoRecord.html?recieveNoticeId=" + recieveNoticeId, true);
			}
		});
	};

	var arrangeStaff = function() {

	};


	//理货人员自动补全
	var clerkPersonAutocomplete = function() {
		clerkName = $(this).val();

		//自动补全
		$("#clerkPerson").autocomplete(seajs.data.handler + "inquireLogisticsClerkPageList.json", {
			minChars: 1,
			max: 10,
			width: 120,
			matchCase: false, //不区分大小写
			scroll: false,
			dataType: 'json',
			scrollHeight: 500,
			//此处为传递而外的参数
			extraParams: {
				pageSize: 50,
				clerkName: function() {
					return $("#clerkPerson").val();
				}
			},
			//需要把data转换成json数据格式                      
			parse: function(data) {
				return $.map(eval(data.datas), function(row) {
					return {
						data: row,
						value: row.clerkName, //此处无需把全部列列出来，只是两个关键列
						result: row.clerkName
					}
				});
			},
			formatItem: function(data, i, total) {
				if ($("#clerkPerson").hasClass('nonemorelist')) {
					$("#clerkPerson").removeClass('nonemorelist');
					return;
				};
				return "<table><tr clerkId=" + data.clerkId + "><td>" + data.clerkName + "(" + data.clerkMobile + ")" + "</td></tr></table>";
			},
			formatMatch: function(data, i, total) {
				return data.clerkName;
			},
			formatResult: function(data, value) {
				return data.clerkName;
			}
		}).result(function(event, data, formatted) { //回调
			$('.clerkId').val(data.clerkId);
			if ($("#clerkPerson").hasClass('nonemorelist')) {
				$("#clerkPerson").removeClass('nonemorelist');
			} else {
				$("#clerkPerson").addClass('nonemorelist');
			};
		});

	}
	var uploadFile = function() {
		if ($("#uploadFile").val() != "") {
			var fileType = "doc,pdf,jpg,png,bmp";
			var prompt = validate.validateFileType($("#uploadFile"), fileType);
			if (prompt.length > 1) {
				base.alert(2, prompt);
				return;
			}
			$.ajaxFileUpload({
				url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
				secureuri: false,
				fileElementId: "uploadFile",
				dataType: 'json',
				success: function(data) {
					var imgSrc = "";
					var html = "";
					imgSrc = data.data[0].fileUuid;
					$("#tallyingFile").val(imgSrc);
				},
				complete: function(xml) {
					$("#uploadFile").on('change', function() {
						uploadFile();
					});
				},
				error: function(data, status, e) {
					if (data.msg == null) {
						base.alert(2, "文件太大无法上传");
					} else {
						base.alert(2, data.msg);
					}
				}
			});
		} else {
			base.alert(3, "请选择文件！");
		}
	}

	//加载收货通知
	var loadTaskDetail = function(recieveNoticeId) {
		base.fnAjax({
			action: "inquireRecieveNoticeDetail.json",
			async: false,
			oData: {
				recieveNoticeId: recieveNoticeId
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					taskDetail = data;
					databind.fillForm($(".tallying"), {
						recieveNoticeId: recieveNoticeId
					});

				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});

	}

	return {
		init: init
	};
});